// pages/login/login.js
Page({
  data: {
    isLoading: false
  },

  onLoad(options) {
    // 检查是否已经登录
    const openid = wx.getStorageSync('openid')
    if (openid) {
      wx.switchTab({
        url: '/pages/edit/edit'
      })
    }
  },

  async onLogin() {
    if (this.data.isLoading) return
    
    this.setData({ isLoading: true })
    
    try {
      // 获取微信登录凭证
      const loginRes = await wx.login()
      if (loginRes.code) {
        // 发送到后端换取openid
        const response = await new Promise((resolve, reject) => {
          const app = getApp();
        wx.request({
          url: app.globalData.api_url + 'api/user/login',
            method: 'POST',
            data: {
              code: loginRes.code
            },
            success: resolve,
            fail: reject
          })
        })
        
        if (response.data && response.data.success) {
          const { openid, token } = response.data.data
          
          // 保存用户信息到本地存储
          wx.setStorageSync('openid', openid)
          wx.setStorageSync('token', token)
          
          wx.showToast({
            title: '登录成功',
            icon: 'success'
          })
          
          // 跳转到修图页面
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/edit/edit'
            })
          }, 1500)
        } else {
          wx.showToast({
            title: response.data.message || '登录失败',
            icon: 'none'
          })
        }
      } else {
        wx.showToast({
          title: '获取登录凭证失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('登录失败:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ isLoading: false })
    }
  }
})